package com.intelligentpension.kotlinbluetooth.bt

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.Context
import com.intelligentpension.kotlinbluetooth.utils.ThreadUtils
import com.orhanobut.logger.Logger


/**
 * 版权：点赞 版权所有
 * author :赵航
 * @e-mail: zhaohangcn@gmail.com
 * time：2022/3/30
 * describe ：
 */
class BtServer internal constructor(mListener: Listener?, var mContext: Context) :
    BtBase(mListener) {
    private val TAG: String = BtServer::class.simpleName!!
    private lateinit var unsafeSocket: BluetoothServerSocket

    init {
        listen()
    }

    @SuppressLint("MissingPermission")
    fun listen() {
        try {
            val mBt: BluetoothAdapter =
                (mContext.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager).adapter
            //var safeSocket= mBt.listenUsingRfcommWithServiceRecord(TAG,SPP_UUID);加密传输,android强制执行配对,弹窗显示配对码
            unsafeSocket =
                mBt.listenUsingInsecureRfcommWithServiceRecord(TAG, SPP_UUID)//明文传输(不安全),无需配对
            ThreadUtils.executeSubThread {
                try {
                    Logger.e("========蓝牙连接之前")
                    var socket: BluetoothSocket = unsafeSocket.accept()//监听连接
                    Logger.e("=======蓝牙连接之后")
                    unsafeSocket.close()//关闭监听,只连接一个设备
                    loopRead(socket)
                } catch (e: Exception) {
                    e.printStackTrace()
                    closeSocket()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun closeSocket() {
        try {
            unsafeSocket.close()//关闭当前的连接
        } catch (e: Exception) {
            e.printStackTrace()
        }
        super.closeSocket()
    }
}